var _openId;
var _shopId;

var Item = function(cartId, num, price, integral) {
	this.cartId = cartId;
	this.num = num;
	this.price = price;
	this.integral = integral;
};

var _items = [];

$(function() {
	_shopId = qmsk.getQueryValue("shopId");
	_openId = qmsk.getQueryValue("openId");

	InitCount();

	$("#recvAdr").val('');
	$("#yin,#goodsSubmit").hide();
	$("#smlbody").hide();
});

/**
 * 加载购物车 数量
 */
function InitCount() {
	qmsk.get('../cart/cartNums/' + _openId, function(response) {
		var count = response.getValue('count');
		if (count > 0) {

			/**
			 * 购物车不为空，此时加载物品和收获人地址信息
			 */
			loadCratList();
			InitValidator();
			loadReceiveInfo(_openId);
			$("#sup").text("(" + count + ")");
		} else {
			$("#sup").text('');
		}
	});
}

/**
 * 加载购物车 数量
 */
function InitCountOnly() {
	qmsk.get('../cart/cartNums/' + _openId, function(response) {
		var count = response.getValue('count');
		if (count > 0) {
			$("#sup").text("(" + count + ")");
		} else {
			$("#sup").text('');
		}
	});
}

function loadReceiveInfo(openId) {

	//同步加载省份
	loadProvince();
	var response = qmsk.asynGet('../cart/receiveInfo/' + openId);
	if (!response.row) {
		// 没有查询到信息
		return;
	}
	var provinceCode = response.getValue("provinceCode");
	if (qmsk.isEmpty(provinceCode)) {
		return;
	}
	$("#province").val(provinceCode);
	provinceSelected();
	$("#city").val(response.getValue("cityCode"));
	citySelected();
	$("#countries").val(response.getValue("countryCode"));
	countriesSelected();
	$("#recvAdr").val(response.getValue("detail"));
	$("#mp").val(response.getValue("mp"));
	$("#receiveName").val(response.getValue("name"));
}

/**
 * 加载购物车列表
 */
function loadCratList() {
	qmsk.get('../cart/list/' + _openId, printGoodsInfoToPage);
}

/**
 * 加载购物项成功回调
 */
function printGoodsInfoToPage(response) {
	$('#goods').empty();
	$("#yin,#goodsSubmit").hide();
	var row = response.row;
	if (row == 0) {
		$("#carJp").show();
		$("#smlbody").hide();
		return;
	}
	$("#smlbody").show();
	$("#carJp").hide();
	_items = [];
	var total = 0;
	var totalIntegral = 0;
	for (var i = 0; i < response.row; i++) {

		var goodsId = response.getValue("goodsId", i);
		var name = response.getValue("goodsName", i);
		var mode = response.getValue("mode", i);
		var price = response.getValue("price", i);
		var num = response.getValue("num", i);
		var imageUrl = response.getValue("imageUrl", i);
		var cartId = response.getValue("cartId", i);
		var integral = response.getValue("integral", i);
		var subTtalIntegral = response.getValue("subTtalIntegral", i);

		//拼接 每件商品的 HTML
		var html = "<div class='product'>" + "<h2><span class='focus'></span>" + name + "</h2>" + "<dl><dt><img src='" + imageUrl + "' /></dt>" + "<dd><p>规格： " + mode + "</p><p>兑换积分：" + "<input class='bolor' type='text' disabled='disabled' value='" + integral + "' /></p></dd></dl>" + "<div class='B_det'>" + "<span onclick='deleteGoods(" + cartId + ")' class='dlt'></span><span>数量：</span>" + "<span class='down' onClick='downNum(" + cartId + ")' >-</span><input id='" + cartId + "_num' onChange='changeNum(" + cartId + ")' class='bolor' type='text' value='" + num + "' /><span class='up' onClick='upNum(" + cartId + ")'>+</span>" + "<b>小计：<input class='bolor' id='" + cartId + "_subTotal'  type='text' disabled='disabled' value='" + subTtalIntegral + "' /></b>" + "</div></div>";

		var item = new Item(cartId, num, price, integral);
		_items.push(item);

		total += (num * price);
		totalIntegral += subTtalIntegral;
		$('#goods').append($(html));

	}
	$("#goodsMoney").val(totalIntegral);
}

function submitBuyCar() {

	if (!$.formValidator.pageIsValid()) {
		$("#goodsSubmit").hide();
		//UI
		$("#yin").hide();
		//UI
		return;
	}

	$("#goodsSubmit").css({
		"margin-left" : -($("#goodsSubmit").width() / 2 + 25) + "px",
		"margin-top" : -($("#goodsSubmit").height() / 2 + 45) + "px"
	});
	$("#goodsSubmit").show();
	$("#yin").show();
}

function subOrder() {
	if (!$.formValidator.pageIsValid()) {
		$("#goodsSubmit").hide();
		//UI
		$("#yin").hide();
		//UI
		return;
	}

	var provinceName = $("#province").find("option:selected").text();
	var cityName = $("#city").find("option:selected").text();
	var countries = $("#countries").val();
	var countriesName = $("#countries").find("option:selected").text();
	var detailAddress = $("#recvAdr").val();
	var receiveName = $("#receiveName").val();
	var mp = $("#mp").val();

	qmsk.post('../order/submit/' + _shopId + '/' + _openId, {
		countries : countries,
		detailAddress : detailAddress,
		receiveName : receiveName,
		mp : mp
	}, function(response) {
		alert('添加成功！');
		qmsk.redirectUrl('order_form.html', {
			shopId : _shopId,
			openId : _openId
		});
	});
}

/**
 * 初始化校验
 */
function InitValidator() {
	$.formValidator.initConfig({
		submitOnce : true,
		formID : "ff",
		onError : function(msg) {
			//alert(msg);
		},
		submitAfterAjaxPrompt : '有数据正在异步验证，请稍等...'
	});
	$("#receiveName").formValidator().inputValidator({
		min : 1,
		onError : "收货人名不能为空"
	});
	$("#recvAdr").formValidator().inputValidator({
		min : 1,
		max : 60,
		onError : "收货地址不能为空,不能超过60字"
	});
	$("#mp").formValidator({
		onShow : "请输入手机号码",
		onFocus : "手机的长度必须是11位",
		onCorrect : "手机合法"
	}).inputValidator({
		min : 11,
		max : 11,
		onError : "手机号码必须为11位"
	}).regexValidator({
		regExp : "mobile",
		dataType : "enum",
		onError : "手机的格式不正确"
	});
	//$("#city").formValidator().inputValidator({min:1,onError: "请选择城市"});
	//$("#province").formValidator().inputValidator({min:1,onError: "请选择省份"});
}

/**
 * 初始化校验
 */
function validator() {
	// 姓名，详细地址，手机号码
	var receiveName = $("#receiveName").val(0);
	if (qmsk.isEmpty(receiveName)) {
		alert('请填写收货人姓名！');
		$("#receiveName").focus();
		return false;
	}
	var recvAdr = $("#recvAdr").val(0);
	if (qmsk.isEmpty(recvAdr)) {
		alert('请填写详细收货地址！');
		return false;
	}
	var mp = $("#mp").val(0);
	if (qmsk.isEmpty(mp)) {
		alert('请填写手机号码！');
		$("#mp").focus();
		return false;
	}

	var mpRegex = /\d{11,11}/g;
	if (!mpRegex.test(mp)) {
		alert('请填写正确的手机号码！');
		$("#mp").focus();
		return false;
	}
	return true;
}

/**
 * 删除订单项
 */
function deleteGoods(cartId) {
	if (!confirm('确认删除吗？')) {
		return;
	}
	qmsk.get('../cart/del/' + cartId, function() {
		loadCratList();
		InitCountOnly();
	});
}

/**
 * 物品数量增加
 */
function upNum(cartId) {
	var num = $("#" + cartId + "_num").val();
	num = parseInt(num) + 1;
	calculate(cartId, num);
}

/**
 * 物品数量减少
 */
function downNum(cartId) {
	var num = $("#" + cartId + "_num").val();
	num = parseInt(num) - 1;
	if (num >= 1) {
		calculate(cartId, num);
	}
}

/**
 * 改变商品数量
 */
function changeNum(cartId) {
	var oldNum = 0;
	for (var i = 0; i < _items.length; i++) {
		if (_items[i].cartId === cartId) {
			oldNum = _items[i].num;
			break;
		}
	}
	var num = $("#" + cartId + "_num").val();
	num = parseInt(num);
	if (num >= 1) {
		calculate(cartId, num);
		$("#" + cartId + "_num").val(num);
	} else {
		$("#" + cartId + "_num").val(oldNum);
	}
}

/**
 * 更新并计算 总价
 */
function calculate(cartId, num) {

	var price;
	var integral;
	var sum = 0;
	for (var i = 0; i < _items.length; i++) {
		var temp = _items[i];
		if (temp.cartId === cartId) {
			temp.num = num;
			price = temp.price;
			integral = temp.integral;
		}
		sum += temp.num * integral;
	}

	qmsk.get('../cart/edit/' + cartId + '/' + num, function() {
		$("#goodsMoney").val(sum);
		$("#" + cartId + "_num").val(num);
		$("#" + cartId + "_subTotal").val(integral * num);
	});
	InitCount();
}

function loadProvince() {
	qmsk.ansyInitSelect({
		id : 'province',
		url : '../location/province',
		heads : ['code', 'name'],
		defaults : {
			key : '选择省'
		}
	});
}

/**
 * 选择好省后加载市
 */
function provinceSelected() {
	var code = $("#province").val();
	if (code !== "选择省" && qmsk.isNotEmpty(code)) {
		qmsk.ansyInitSelect({
			id : 'city',
			url : '../location/city/' + code,
			heads : ['code', 'name'],
			defaults : {
				key : '选择市'
			}
		});
		$("#city").show();
	} else {
		$("#city").empty();
		$("#city").hide();
	}
	$("#countries").empty();
	$("#countries").hide();
	$("#recvAdr").val('');
	$("#detailAddrTr").hide();
}

/**
 * 选择号市后 加载区县
 */
function citySelected() {
	var code = $("#city").val();
	if (qmsk.isNotEmpty(code)) {
		qmsk.ansyInitSelect({
			id : 'countries',
			url : '../location/countries/' + code,
			heads : ['code', 'name'],
			defaults : {
				key : '选择区县'
			}
		});
		$("#countries").show();
	} else {
		$("#countries").empty();
		$("#countries").hide();
	}
	$("#recvAdr").val('');
	$("#detailAddrTr").hide();
}

/**
 * 选择号区县后 加载输入框
 */
function countriesSelected() {
	var code = $("#countries").val();
	if (qmsk.isNotEmpty(code)) {
		$("#recvAdr").val('');
		$("#detailAddrTr").show();
	}
}

/**
 * 订单页面
 */
function selectOrder() {
	qmsk.redirectUrl('order_form.html', {
		shopId : _shopId,
		openId : _openId
	});
}

/**
 * 商品里列表页面
 */
function cancelOrder() {
	$("#goodsSubmit").hide();
	window.location.href = "products.html?shopId=" + _shopId + "&openId=" + _openId + "&mId=" + _mId;
}

/**
 * 到购物车页面
 */
function toBuyCar() {
	qmsk.redirectUrl('buy_car.html', {
		shopId : _shopId,
		openId : _openId
	});
}

/**
 * 刷新
 */
function myrefresh() {
	window.location.reload();
}

/**
 * 商品列表页面
 */
function toOrderForm() {
	qmsk.redirectUrl('order_form.html', {
		shopId : _shopId,
		openId : _openId
	});
}

/**
 * 商品列表页面
 */
function toProducts() {
	qmsk.redirectUrl('products.html', {
		shopId : _shopId,
		openId : _openId
	});
}

